package com.cxd.web.backend;

import com.cxd.entity.EbProduct;
import com.cxd.entity.EbProductCategory;
import com.cxd.entity.EbUser;
import com.cxd.service.IEbProductCategoryService;
import com.cxd.service.IEbProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/product")     //工号
public class ProductController {
    @Autowired  //spring帮我们将NewsService的对象创建出来
    private IEbProductService productService;
    @Autowired
    private IEbProductCategoryService iEbProductCategoryService;

    /**
     * 获取分页新闻信息
     *
     * @return /**
     * model 将web层的数据传递jsp页面
     */
    @RequestMapping("/list")
    public String list(HttpSession session,Model model,
                       @RequestParam(value = "page", defaultValue = "1") int psize,
                       @RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);

        System.out.println("receive request!!;psize==>" + psize);
        List<EbProduct> productList = productService.listByPage(psize, pageSize);
        final Integer totalPage = productService.findTotalPage(pageSize);

        model.addAttribute("productList", productList);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currPage", psize);
        model.addAttribute("tag",3);


        return "manage/product";//跳转到/manage/news.jsp 将数据显示出来
    }

    @RequestMapping("/to_save")
    public String toSave(HttpSession session,Model model) {
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        List<EbProductCategory> ebProductCategories = iEbProductCategoryService.listByPage();
        List<EbProductCategory> parentCategory = new ArrayList<>();
        List<EbProductCategory> orderlyCategory = new ArrayList<>();
        for (int i = 0;i < ebProductCategories.size();++i){
            if(ebProductCategories.get(i).getEpcId()==ebProductCategories.get(i).getEpcParentId()){
                parentCategory.add(ebProductCategories.get(i));
                orderlyCategory.add(ebProductCategories.get(i));
                for (int m = 0;m < ebProductCategories.size();++m){
                    if (ebProductCategories.get(i).getEpcId()==ebProductCategories.get(m).getEpcParentId()
                            &&ebProductCategories.get(m).getEpcId()!=ebProductCategories.get(m).getEpcParentId()){
                        orderlyCategory.add(ebProductCategories.get(m));
                    }
                }
            }
        }
        model.addAttribute("productCategoryList",orderlyCategory);
        model.addAttribute("tag",3);
        return "manage/product-add";
    }


    @RequestMapping("/save")
    public String save(HttpSession session,HttpServletRequest request,MultipartFile productFileName, EbProduct ebProduct,Model model,int classId){
//        System.out.println("in");
        //
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        //服务器的路径

        String path = request.getServletContext().getRealPath("/WEB-INF/images/product/");
        System.out.println("path===>"+path);
        String pathLocal = "F:/easybuy-cxd05/src/main/webapp/WEB-INF/images/product/";
        String fileName = productFileName.getOriginalFilename();
        String newName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        File uploadPic = new File(path + newName);
        File uploadPicLocal = new File(pathLocal + newName);
//        System.out.println(newName);
        try {
            if (!uploadPic.exists()){
                uploadPic.mkdirs();
            }
            productFileName.transferTo(uploadPic);
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            if (!uploadPicLocal.exists()){
                uploadPicLocal.mkdirs();
            }
            productFileName.transferTo(uploadPicLocal);
        }catch (Exception e){
            e.printStackTrace();
        }
 //          System.out.println("3");
        ebProduct.setEpFileName(newName);
        /*
        * 注意：
        * 目前还没有和产品分类表对接
        * 所以直接使用无效值，
        * 之后需要更改*/
        EbProductCategory ebProductCategory = iEbProductCategoryService.selectByCondition(classId);
        ebProduct.setEpcChildId(classId);
        ebProduct.setEpcId(ebProductCategory.getEpcParentId());
//        System.out.println(ebProduct);
        int num = productService.save(ebProduct);
        model.addAttribute("tag",3);
        model.addAttribute("result",num);

        return "/manage/manage-result";

    }





    @RequestMapping("/to_edit")
    public String toEdit(HttpSession session,Model model, @RequestParam("epId") int epId) {
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        System.out.println("点击修改跳过来了，epId=" + epId);
        EbProduct ebProduct = productService.selectOne(epId);
        List<EbProductCategory> ebProductCategories = iEbProductCategoryService.listByPage();
        List<EbProductCategory> parentCategory = new ArrayList<>();
        List<EbProductCategory> orderlyCategory = new ArrayList<>();
        for (int i = 0;i < ebProductCategories.size();++i){
            if(ebProductCategories.get(i).getEpcId()==ebProductCategories.get(i).getEpcParentId()){
                parentCategory.add(ebProductCategories.get(i));
                orderlyCategory.add(ebProductCategories.get(i));
                for (int m = 0;m < ebProductCategories.size();++m){
                    if (ebProductCategories.get(i).getEpcId()==ebProductCategories.get(m).getEpcParentId()
                            &&ebProductCategories.get(m).getEpcId()!=ebProductCategories.get(m).getEpcParentId()){
                        orderlyCategory.add(ebProductCategories.get(m));
                    }
                }
            }
        }
        model.addAttribute("productCategoryList",orderlyCategory);
        model.addAttribute("ebProduct", ebProduct);
        model.addAttribute("tag",3);
        return "manage/product-modify";
    }


    @RequestMapping("/edit")
    public String edit(HttpSession session,HttpServletRequest request,MultipartFile productFileName, EbProduct ebProduct,Model model,int classId){
//
//        System.out.println("in");
        //
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        //服务器的路径
        String path = request.getServletContext().getRealPath("/WEB-INF/images/product/");
        System.out.println("path===>"+path);
        String pathLocal = "F:/easybuy-cxd05/src/main/webapp/WEB-INF/images/product/";
        String fileName = productFileName.getOriginalFilename();
        String newName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        File uploadPic = new File(path + newName);
        File uploadPicLocal = new File(pathLocal + newName);
//        System.out.println(newName);
        try {
            if (!uploadPic.exists()){
                uploadPic.mkdirs();
            }
            productFileName.transferTo(uploadPic);
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            if (!uploadPicLocal.exists()){
                uploadPicLocal.mkdirs();
            }
            productFileName.transferTo(uploadPicLocal);
        }catch (Exception e){
            e.printStackTrace();
        }
        //          System.out.println("3");
        ebProduct.setEpFileName(newName);
        /*
         * 注意：
         * 目前还没有和产品分类表对接
         * 所以直接使用无效值，
         * 之后需要更改*/
        ebProduct.setEpcId(1);
//        System.out.println(ebProduct);
        int num = productService.updateProduct(ebProduct);
        EbProductCategory ebProductCategory = iEbProductCategoryService.selectByCondition(classId);
        ebProduct.setEpcChildId(classId);
        ebProduct.setEpcId(ebProductCategory.getEpcParentId());
        model.addAttribute("tag",3);
        model.addAttribute("result",num);

        return "/manage/manage-result";

}

    @RequestMapping("/delete")
    public String delete(HttpSession session,Integer id,Model model){
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        int result = productService.deleteByPk(id);
        model.addAttribute("tag",3);
        model.addAttribute("result",result);
        return "manage/manage-result";
    }



}

